package com.hxkcloud.nurse.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hxkcloud.nurse.R;
import com.hxkcloud.nurse.beans.resultbeans.ObjectResultBean;
import com.hxkcloud.nurse.dborm.LoginInfoDao;
import com.hxkcloud.nurse.popup.DateSelectorPopWindow;
import com.hxkcloud.nurse.popup.DateTimeSelectPopWindow;
import com.hxkcloud.nurse.popup.DaysSelectPopWindow;
import com.hxkcloud.nurse.request.MessageCode;
import com.hxkcloud.nurse.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.nurse.utils.StringUtil;
import com.hxkcloud.nurse.utils.Utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by ray_lei on 2016/7/14.
 */
public class PregnantEditInfoActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;
    private TextView tv_edit;

    private EditText zhouqiET;
    private EditText starttimeET;
    private EditText birthdateET;

    private String menstrualStartDate = "";
    private String menstrualCycle = "";
    private String birthDate = "";

    private boolean zhouqiInput = false;
    private boolean starttimeInput = false;
    private boolean birthInput = false;

    private Button saveBtn;


    private DaysSelectPopWindow daysPop;
    private DateSelectorPopWindow dateSelect;
    private DateTimeSelectPopWindow datetimeSelect;

    private ObjectResultBean<String> resultBean;

    private String isFromJoin = "";
    private String departmentId = "";

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_SUBMITMYDELIVERYINFO_SUCCESS:
                if (msg.obj != null) {
                    resultBean = (ObjectResultBean<String>) msg.obj;
//                    SharedPreferenceUtil.setYunzhou(mContext, zhouqiET.getText().toString());
//                    SharedPreferenceUtil.setFenmiantime(mContext, birthdateET.getText().toString());
//                    SharedPreferenceUtil.setStarttime(mContext, starttimeET.getText().toString());
                    toastMsg(resultBean.getMessage());
                    if ("true".equals(isFromJoin)) {
                        loading();
                        YiJiaHuNetWorkUtils.departmentJoin(departmentId, loginInfo.getUserId(), handler);
                    } else {
                        finish();
                    }

                }

                break;
            case MessageCode.NETWORKCODE_SUBMITMYDELIVERYINFO_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                    return;
                }

                break;
            case MessageCode.NETWORKCODE_DEPARTMENTJOIN_SUCCESS:
                loginInfo.setDepartmentId(departmentId);
                LoginInfoDao loginInfoDao = new LoginInfoDao(mContext);
                loginInfoDao.setUser(loginInfo);
                Intent iBack = new Intent();
                setResult(RESULT_OK, iBack);
                finish();
                break;
            case MessageCode.NETWORKCODE_DEPARTMENTJOIN_FAILURE:
                if (msg.obj != null) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.departmentjoinfail);
                }
                break;

        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout_pregnantedit);
        isFromJoin = getIntent().getStringExtra("isFromJoin");
        departmentId = getIntent().getStringExtra("departmentId");

        menstrualStartDate = getIntent().getStringExtra("menstrualStartDate");
        menstrualCycle = getIntent().getStringExtra("menstrualCycle");
        birthDate = getIntent().getStringExtra("birthDate");

        initView();
        initData();
        initListener();
    }

    @Override
    protected void initView() {

        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        tv_title.setText(getResources().getText(R.string.pregnantinfo_text_title));
        iv_back.setOnClickListener(this);


        zhouqiET = (EditText) findViewById(R.id.pregnantedit_et_zhouqi);
        starttimeET = (EditText) findViewById(R.id.pregnantedit_et_starttime);
        birthdateET = (EditText) findViewById(R.id.pregnantedit_et_birthdate);

        zhouqiET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (StringUtil.isEmpty(s.toString())) {
                    zhouqiInput = false;
                    saveBtn.setBackgroundResource(R.drawable.bt_grey);
                    saveBtn.setEnabled(false);
                } else {
                    zhouqiInput = true;
                    if (starttimeInput) {
                        saveBtn.setBackgroundResource(R.drawable.bt_green);
                        saveBtn.setEnabled(true);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        starttimeET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (StringUtil.isEmpty(s.toString())) {
                    starttimeInput = false;
                    saveBtn.setBackgroundResource(R.drawable.bt_grey);
                    saveBtn.setEnabled(false);
                } else {
                    starttimeInput = true;
                    if (zhouqiInput) {
                        saveBtn.setBackgroundResource(R.drawable.bt_green);
                        saveBtn.setEnabled(true);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

//        birthdateET.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                if (StringUtil.isEmpty(s.toString())) {
//                    birthInput = false;
//                    saveBtn.setBackgroundResource(R.drawable.bt_grey);
//                    saveBtn.setEnabled(false);
//                } else {
//                    birthInput = true;
//                    if (starttimeInput && zhouqiInput) {
//                        saveBtn.setBackgroundResource(R.drawable.bt_blue);
//                        saveBtn.setEnabled(true);
//                    }
//                }
//            }

//            @Override
//            public void afterTextChanged(Editable s) {
//
//            }
//        });

        saveBtn = (Button) findViewById(R.id.pregnantedit_btn_save);
    }

    @Override
    protected void initListener() {
        iv_back.setOnClickListener(this);
        zhouqiET.setOnClickListener(this);
        starttimeET.setOnClickListener(this);
        birthdateET.setOnClickListener(this);
        saveBtn.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        if ("true".equals(isFromJoin)) {
            zhouqiET.setText("");
            starttimeET.setText("");
            birthdateET.setText("");
        } else {
//            zhouqiET.setText(SharedPreferenceUtil.getYunZhou(mContext));
//            starttimeET.setText(SharedPreferenceUtil.getStarttime(mContext));
//            birthdateET.setText(SharedPreferenceUtil.getFenmiantime(mContext));
            zhouqiET.setText(menstrualCycle);
            starttimeET.setText(menstrualStartDate);
            birthdateET.setText(birthDate);

        }

    }

    public int compareDate(String DATE1, String DATE2, String format) {

        DateFormat df = new SimpleDateFormat(format);
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() > dt2.getTime()) {
                System.out.println("dt1 在dt2前");
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                System.out.println("dt1在dt2后");
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back://back
                finish();
                break;
            case R.id.pregnantedit_et_zhouqi:
                if (daysPop == null) {
                    daysPop = new DaysSelectPopWindow(this);

                }
                daysPop.setDaysListener(new DaysSelectPopWindow.DaysListener() {

                    @Override
                    public void setDays(String days) {
                        zhouqiET.setText(days);
                    }
                });
                daysPop.show(ll_title);

                break;
            case R.id.pregnantedit_et_starttime:
                if (dateSelect == null) {
                    dateSelect = new DateSelectorPopWindow(this);
                    dateSelect.setTimeListener(new DateSelectorPopWindow.TimeListener() {
                        @Override
                        public void setTime(String time) {
                            String timeStr = "";
                            if (time.contains(".")) {
                                timeStr = time.replace(".", "-");
                            }
                            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                            String currentDate = df.format(new Date());
                            int i = compareDate(currentDate, timeStr, "yyyy-MM-dd");

                            if (i == 0 || i == 1) {
                                String bds = birthdateET.getText().toString();
                                if (!TextUtils.isEmpty(bds)) {
                                    long bdl = 0;
                                    long sdl = 0;
                                    try {
//                                        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                                        bdl = df.parse(bds).getTime();
                                        sdl = df.parse(timeStr).getTime();
                                    } catch (ParseException e) {
                                    }
                                    if (bdl <= sdl) {
                                        toastMsg("您的分娩时间不能早于末次月经开始时间");
                                    } else {
                                        starttimeET.setText(timeStr);
                                    }

                                } else {
                                    starttimeET.setText(timeStr);
                                }
                            } else {
                                toastMsg(R.string.input_right_date);
                            }

                        }
                    });
                }
                dateSelect.show(ll_title);
                break;
            case R.id.pregnantedit_et_birthdate:
                if (datetimeSelect == null) {
                    datetimeSelect = new DateTimeSelectPopWindow(this);
                    datetimeSelect.setTimeListener(new DateTimeSelectPopWindow.TimeListener() {
                        @Override
                        public void setTime(String time) {
                            String timeStr = "";
                            if (time.contains(".")) {
                                timeStr = time.replace(".", "-");
                            }
                            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                            String currentDate = df.format(new Date());
                            int i = compareDate(currentDate, timeStr, "yyyy-MM-dd HH:mm");
                            if (i == 0 || i == 1) {
                                String sds = starttimeET.getText().toString().trim();
                                if (!TextUtils.isEmpty(sds)) {
                                    long sdl = 0;
                                    long bdl = 0;
                                    try {
                                        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
                                        sdl = df1.parse(sds).getTime();
                                        bdl = df1.parse(timeStr).getTime();
                                    } catch (ParseException e) {
                                    }
                                    if (bdl <= sdl) {
                                        toastMsg("您的分娩时间不能早于末次月经开始时间");
                                    } else {
                                        birthdateET.setText(timeStr);
                                    }
                                } else {
                                    birthdateET.setText(timeStr);
                                }
                            } else {
                                toastMsg(R.string.input_right_date);
                            }

                        }
                    });
                }
                datetimeSelect.show(ll_title);

                break;
            case R.id.pregnantedit_btn_save:
                loading();
                String zhouqi = zhouqiET.getText().toString();
                String zhouqiStr = zhouqi.substring(0, zhouqi.length() - 1);
                String starttime = starttimeET.getText().toString();
                String birthday = birthdateET.getText().toString();
                YiJiaHuNetWorkUtils.submitDeliveryCycleInfo(loginInfo.getUserId(), departmentId, zhouqiStr, Utils.date2TimeStamp(starttime, "yyyy-MM-dd"), Utils.date2TimeStamp(birthday, "yyyy-MM-dd HH:mm"), handler);
                break;
        }
    }
}
